/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Login.java
 *
 * Created on 09-nov-2011, 16:37:35 
 */
package clienteSandraParada;


import Usuario.DialogoInfoUsuarioAdministracion;
import com.l2fprod.common.swing.plaf.LookAndFeelAddons;
import com.l2fprod.common.swing.plaf.windows.WindowsLookAndFeelAddons;
import java.awt.Frame;
import java.awt.event.KeyEvent;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import service.Usuario;


/**
 *
 * @author Franzel
 */
public class Login extends javax.swing.JFrame {
     private Ventana ventana;
     static service.Usuario user;
    
    /** Creates new form Login */
    public Login() {
        initComponents();
        setIconImage(new ImageIcon(getClass().getResource("/GUI/Img/logo2.png")).getImage());
        this.setLocationRelativeTo(null);  
        //agregarUsuario(CrearUsuarioPorDefecto());           
        List<service.Usuario> usuarios = listarUsuarios();
        
        if(usuarios!=null && usuarios.isEmpty()){
            JOptionPane.showMessageDialog(this,"No existen usuarios en la base de datos, debe crear una cuenta administrador");            
            DialogoInfoUsuarioAdministracion dialogoUsuario = new DialogoInfoUsuarioAdministracion(null, true, null);
            dialogoUsuario.limpiarCampos();
            dialogoUsuario.habilitarCampos(true);
            dialogoUsuario.setTitle("Agregar Usuario");
            dialogoUsuario.setModal(true);
            dialogoUsuario.campoTipoCuenta.setText("Administrador");
            dialogoUsuario.campoTipoCuenta.setEnabled(false);
            dialogoUsuario.botonFormularioAccion.setText("Agregar");
            dialogoUsuario.botonFormularioAccion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Agregar.png")));                         
            dialogoUsuario.setVisible(true);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        campoUsuario = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        campoContrasenia = new javax.swing.JPasswordField();
        botonAcceder = new javax.swing.JButton();
        botonCancelar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Iniciar Sesión");
        setIconImage(getIconImage());
        setResizable(false);

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/logo.png"))); // NOI18N

        jLabel2.setText("Usuario: ");

        campoUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                campoUsuarioActionPerformed(evt);
            }
        });

        jLabel3.setText("Contraseña: ");

        campoContrasenia.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                campoContraseniaActionPerformed(evt);
            }
        });

        botonAcceder.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Aceptar.png"))); // NOI18N
        botonAcceder.setText("Acceder");
        botonAcceder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonAccederActionPerformed(evt);
            }
        });

        botonCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Cancelar.png"))); // NOI18N
        botonCancelar.setText("Cancelar");
        botonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(campoContrasenia)
                            .addComponent(campoUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, 171, Short.MAX_VALUE))
                        .addGap(75, 75, 75))))
            .addGroup(layout.createSequentialGroup()
                .addGap(106, 106, 106)
                .addComponent(botonAcceder)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(botonCancelar)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(campoUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(14, 14, 14)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(campoContrasenia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botonAcceder)
                    .addComponent(botonCancelar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    
    private void botonAccederActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonAccederActionPerformed
        
       validarUsuarioContrasenia();
      
    }//GEN-LAST:event_botonAccederActionPerformed

    private void botonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonCancelarActionPerformed
        // TODO add your handling code here:
        System.exit(0);
    }//GEN-LAST:event_botonCancelarActionPerformed

    private void campoContraseniaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_campoContraseniaActionPerformed
        // TODO add your handling code here:    
        this.botonAccederActionPerformed(null);
    }//GEN-LAST:event_campoContraseniaActionPerformed

    private void campoUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_campoUsuarioActionPerformed

        // TODO add your handling code here:
        this.botonAccederActionPerformed(null);
    }//GEN-LAST:event_campoUsuarioActionPerformed

    /**
     * @param args the command line arguments
     */
    
    public static void main(String args[]) {
      
                /* Set the Nimbus look and feel */
                //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
                /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
                 * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
                 */
                       try {
                            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                                LookAndFeelAddons.setAddon(WindowsLookAndFeelAddons.class);
                        //try{
                          //  UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");

       
                        } catch (Exception e) {
                
                        }

            //</editor-fold>
            /* Create and display the form */
            new Login().setVisible(true);

        
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonAcceder;
    private javax.swing.JButton botonCancelar;
    private javax.swing.JPasswordField campoContrasenia;
    private javax.swing.JTextField campoUsuario;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    // End of variables declaration//GEN-END:variables
    
    public void validarUsuarioContrasenia(){
        String usuario = campoUsuario.getText();
        String contrasenia = new String(campoContrasenia.getPassword());
        String contraseñaEncriptada= getStringMessageDigest(contrasenia);
        java.util.List<service.Usuario> usuarios = null;
        
        usuarios=Login.listarUsuarios();
        
        
        if(usuarios!=null){
            user=new service.Usuario();      
            boolean encontrado=false;
            for(int i = 0; i< usuarios.size(); i++ ){
                if(usuarios.get(i).getUsuario().equals(usuario)){
                    System.out.println("tipo= " +user.getTipoCuenta());
                    user=usuarios.get(i);
                    encontrado=true;
                    break;
                }
            }
            if (encontrado){
                 if(user.getContrasenia().equals(contraseñaEncriptada)){
                     this.setVisible(false);
                     //crear Bitacora()
                     ventana=new Ventana();
                     ventana.setExtendedState(JFrame.MAXIMIZED_BOTH);
                     ventana.setVisible(true);
                 }
                 else{
                    JOptionPane.showMessageDialog(this,"Datos incorrectos, Ingrese Nuevamente","Advertencia", JOptionPane.WARNING_MESSAGE);
                 }

             }
             else{
                 JOptionPane.showMessageDialog(this,"Datos incorrectos, Ingrese Nuevamente","Advertencia", JOptionPane.WARNING_MESSAGE);
             }
    }
    }

    public static Usuario getUser() {
        return user;
    }

    public static void setUser(Usuario user) {
        Login.user = user;
    }

   
   /***
     * Encripta un mensaje de texto mediante algoritmo de resumen de mensaje.
     * @param message texto a encriptar
     * @param algorithm algoritmo de encriptacion, puede ser: MD2, MD5, SHA-1, SHA-256, SHA-384, SHA-512
     * @return mensaje encriptado
     */
    public static String getStringMessageDigest(String message){
        String algorithm="MD5";
        byte[] digest = null;
        byte[] buffer = message.getBytes();
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            messageDigest.reset();
            messageDigest.update(buffer);
            digest = messageDigest.digest();
        } catch (NoSuchAlgorithmException ex) {
            System.out.println("Error creando Digest");
        }
        return toHexadecimal(digest);
    }

          /***
     * Convierte un arreglo de bytes a String usando valores hexadecimales
     * @param digest arreglo de bytes a convertir
     * @return String creado a partir de <code>digest</code>
     */
    private static String toHexadecimal(byte[] digest){
        String hash = "";
        for(byte aux : digest) {
            int b = aux & 0xff;
            if (Integer.toHexString(b).length() == 1) hash += "0";
            hash += Integer.toHexString(b);
        }
        return hash;
    }

    private static java.util.List<service.Usuario> listarUsuarios() {
        service.UsuarioWSService service = null;
        service.UsuarioWS port = null;
        try{
            service = new service.UsuarioWSService();
            port = service.getUsuarioWSPort();
            return port.listarUsuarios();
        }
        catch(Exception e){                        
            JOptionPane.showMessageDialog(null, "No hay conexión con el servidor, encienda el servidor. \n Si ya lo hizo comuniquese con el mantenedor del sistema", "Error", JOptionPane.ERROR_MESSAGE);
        }
        return null;
        
    }
}
